<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2016/7/23
 * Time: 0:02
 */
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Http\Requests\Request;
use DB;

class BaseController extends Controller
{
    public function __construct()
    {
        date_default_timezone_set('Asia/Shanghai');
        // 载入父级
        parent::__construct();
        if(empty(session('User')))
        {
            header('Location:'.__BASE__.'home/login');
            die();
        }
    }

    private static function formatMenu($menuList)
    {
        if(!empty($menuList))
        {
            foreach($menuList as $k => $v)
            {
                $res = DB::table('menulist')
                    ->where(['status'=>1,'showwhere'=>1,'pid'=>$v->id])
                    ->orderBy('sort','asc')
                    ->get();
                $menuList[$k]->_child =self::formatMenu($res);
            }
        }
        return $menuList;
    }

    /**
     * 获取某个主播的在线状态
     * User: Xiahuiqin
     *
     * @param $member_id
     *
     * @return string
     */
    public function getOneAnchorStatus($member_id)
    {
        if(!empty($member_id))
        {
            $anchor_statusAll = DB::table('member_online')->where('member_id',$member_id)->first();
            if(!empty($anchor_statusAll))
            {
                return $anchor_statusAll->status;
            }else{
                return 0;
            }
        }else{
            return 0;
        }
    }


    /**
     * token验证
     * User: Xiahuiqin
     *
     * @param $token
     *
     * @return int
     */
    public function checkToken($token)
    {
        $findUser = DB::table('member')->where('token',$token)->where('status',1)->first();
        if(!empty($findUser)){
            if(time()>$findUser->time_out){
                //过期
                return -9001;
            }else{
                //刷新token过期时间
//                DB::table('member')->where('id',$findUser->id)->update(array('time_out'=>time()));
//                return 9000;
                return $findUser;
            }
        }else{
            return -9002; //token无效
        }
    }

    /**
     * 聚合数据 发短信验证码
     * User: Xiahuiqin
     */
    public function sendSmsBase($mobile)
    {
        if(empty($mobile)) return -1;
        header('content-type:text/html;charset=utf-8');

        $sendUrl = 'http://v.juhe.cn/sms/send'; //短信接口的URL
        // 生成一个 "随机" 字母数字字符串. Str::quickRandom($length = 16)
        $code = rand(1000,9999);
        $smsConf = array(
            'key'   => 'beb430e383177157bce317c55349a86e', //您申请的APPKEY
            'mobile'    => $mobile, //接受短信的用户手机号码
            'tpl_id'    => '98961', //您申请的短信模板ID，根据实际情况修改
            'tpl_value' =>'#code#='.$code //您设置的模板变量，根据实际情况修改
        );

        $content = $this->juhecurl($sendUrl,$smsConf,1); //请求发送短信

        if($content){
            $result = json_decode($content,true);
            $error_code = $result['error_code'];
            if($error_code == 0){
                //状态为0，说明短信发送成功
//                echo "短信发送成功,短信ID：".$result['result']['sid'];
                \Cache::put('sms_'.$mobile,$code,30);  //短信时长30分钟

                $arr['code'] = 0;
                $arr['msg'] = '短信发送成功';
                return $arr;
            }else{
                //状态非0，说明失败
//                $msg = $result['reason'];
//                echo "短信发送失败(".$error_code.")：".$msg;

                $arr['code'] = $error_code;
                $arr['msg'] = $result['reason'];
                return $arr;
            }
        }else{
            //返回内容异常，以下可根据业务逻辑自行修改
//            echo "请求发送短信失败";
            return -1;
        }
    }

    /**
     * 验证短信码是否有效
     * User: Xiahuiqin
     *
     * @param $mobile
     * @param $code
     *
     * @return int
     */
    public function checkSms($mobile,$code)
    {
        $m_code = \Cache::get('sms_'.$mobile);
        if(!empty($m_code) && $m_code==$code){
            return 1;
        }else{
            return 0;
        }
    }

    /**
     * 请求接口返回内容
     * @param  string $url [请求的URL地址]
     * @param  string $params [请求的参数]
     * @param  int $ipost [是否采用POST形式]
     * @return  string
     */
    public function juhecurl($url,$params=false,$ispost=0){
        $httpInfo = array();
        $ch = curl_init();
        curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
        curl_setopt( $ch, CURLOPT_USERAGENT , 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22' );
        curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 30 );
        curl_setopt( $ch, CURLOPT_TIMEOUT , 30);
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );
        if( $ispost )
        {
            curl_setopt( $ch , CURLOPT_POST , true );
            curl_setopt( $ch , CURLOPT_POSTFIELDS , $params );
            curl_setopt( $ch , CURLOPT_URL , $url );
        }
        else
        {
            if($params){
                curl_setopt( $ch , CURLOPT_URL , $url.'?'.$params );
            }else{
                curl_setopt( $ch , CURLOPT_URL , $url);
            }
        }
        $response = curl_exec( $ch );
        if ($response === FALSE) {
            //echo "cURL Error: " . curl_error($ch);
            return false;
        }
        $httpCode = curl_getinfo( $ch , CURLINFO_HTTP_CODE );
        $httpInfo = array_merge( $httpInfo , curl_getinfo( $ch ) );
        curl_close( $ch );
        return $response;
    }

    /**
     * 下级消费了，上级提成
     * User: Xiahuiqin
     *
     * @param $member_id  消费人id
     * @param $e_money  消费金额
     */
    public function pidShared($member_id,$e_money)
    {
        $member =  DB::table('member')->where('id',$member_id)->where('status',1)->first();
        if(!empty($member->pid)){
            $pUser = DB::table('member')->where('id',$member->pid)->where('status',1)->first();
            if(!empty($pUser)){
                $findPlan = DB::table('admini_systeminfo')->select('anchor_proportions','plan_proportions','video_price')->first();
                if($member->user_role==3 && $member->auth_status==2){
                    //主播是主播的价，普通用户是普通用户的价
                    $rate = $findPlan->anchor_proportions;
                }else{
                    $rate = $findPlan->plan_proportions;
                }
                $fcMoney = ($e_money*$rate)/100;
                $fcMoney = intval($fcMoney);

                $insertRA['member_id'] = $member->pid;
                $insertRA['create_time'] = time();
                $insertRA['e_money'] = $fcMoney;
                $insertRA['operate_status'] = 1;
                $insertRA['type'] = 6;
                DB::table('member_recharge')->insertGetId($insertRA);
            }
        }
    }

    /**
     * 获取用户等级
     * User: Xiahuiqin
     *
     * @param $member_id
     *
     * @return string
     */
    public function getUserLevel($member_id)
    {
        $level = \Helpers::getUserLevel($member_id);

        return $level;
    }

    /**
     * 验证sign的有效性
     * User: Xiahuiqin
     *
     * @param $check_id
     *
     * @return int
     */
    public function checkSign($check_id='')
    {
//        return 1;
        if(empty($_REQUEST['sign'])){
            return 0;
        }
        $sign = $_REQUEST['sign'];
        $secret_key = '9b4aaf?&&##664bdef@c3fc3efa9';
        $time0 = time(); //当前时间戳

        if(!empty($check_id)){
            $signArr[0] = md5($check_id.$time0.$secret_key);
        }else{
            $signArr[0] = md5($time0.$secret_key);
        }
        //当前时间戳前 i s往后
        for($i=1;$i<30;$i++){
            $str[$i] = $time0 + $i;
            if(!empty($check_id)){
                $signArr[$i] = md5($check_id.$str[$i].$secret_key);
            }else{
                $signArr[$i] = md5($str[$i].$secret_key);
            }
        }
        //当前时间戳前 i s往前
        for($j=1;$j<30;$j++){
            $strj[$j] = $time0 - $j;
            if(!empty($check_id)){
                $signArr[30+$j] = md5($check_id.$strj[$j].$secret_key);
            }else{
                $signArr[30+$j] = md5($check_id.$strj[$j].$secret_key);
            }

        }
        if(!in_array($sign,$signArr)){
            return 0;
        }else{
            return 1;
        }
    }
}